<template>
  <!--  系统变量页面-->
  <div class="page">
    <!-- 条件筛选 -->
    <div class="page_filter">
      <el-input v-model="form.pointId" clearable placeholder="监测点ID"></el-input>
      <el-button class="common_btn-defalut" icon="el-icon-search" @click="form.page=1;queryList()">搜索</el-button>
    </div>
    <div class="page_main">
      <el-button icon="el-icon-plus" @click.stop="handleAdd" class="common_btn-small">新增虚拟设备</el-button>
      <!-- table -->
      <el-table
        :data="tableList"
        border>
        <el-table-column
          label="序号"
          fixed
          width="80">
          <template slot-scope="scope">
            {{getIndex(scope.$index)}}
          </template>
        </el-table-column>
        <el-table-column prop="pointId" label="监测点ID" width="200"></el-table-column>
        <el-table-column prop="dataJson" label="数据JSON" show-overflow-tooltip min-width="200"></el-table-column>
        <el-table-column prop="tempJson" label="温度JSON" show-overflow-tooltip min-width="200"></el-table-column>
        <el-table-column prop="timeInterval" label="数据时间间隔" min-width="120"></el-table-column>
        <el-table-column prop="rand" label="浮动范围" min-width="100"></el-table-column>
        <el-table-column prop="k" label="补偿系数" min-width="100"></el-table-column>
        <el-table-column prop="remark" label="备注说明" min-width="200"></el-table-column>
        <el-table-column
          label="创建时间"
          width="180">
          <template slot-scope="scope">{{scope.row.createTime | formatTimer}}</template>
        </el-table-column>
        <el-table-column
          label="更新时间"
          width="180">
          <template slot-scope="scope">{{scope.row.updateTime | formatTimer}}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="210">
          <template slot-scope="scope">
            <el-button type="text" class="btn_edit" @click="handleEdit(scope.row)">编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="form.page"
        :page-size="form.pageSize"
        :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
        layout="sizes, prev, pager, next"
        :total="form.total">
      </el-pagination>
    </div>

    <!-- 新增编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="isShowDialog" :close-on-click-modal="false" width="800px">
      <!-- 具体form表单 -->
      <el-form label-position="right" ref="form" :rules="rules" :model="currentRow" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="监测点ID" prop="pointId">
              <el-input v-model="currentRow.pointId" placeholder="请输入监测点ID"></el-input>
            </el-form-item>
            <el-form-item label="浮动范围" prop="name">
              <el-input v-model="currentRow.rand" type="number" placeholder="数据波动范围"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="补偿系数" prop="name">
              <el-input v-model="currentRow.k" type="number" placeholder="温度补偿系数"></el-input>
            </el-form-item>
            <el-form-item label="数据时间间隔" prop="name">
              <el-input v-model="currentRow.timeInterval" type="number" placeholder="数据时间间隔(分钟)"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="数据JSON" prop="value">
          <el-input v-model="currentRow.dataJson" type="textarea" :autosize="{ minRows: 8}"
                    placeholder="请输入值"></el-input>
        </el-form-item>
        <el-form-item label="温度JSON" prop="value">
          <el-date-picker size="mini" v-model="temp.time" type="date" placeholder="选择日期"></el-date-picker>
          <el-button size="mini"  type="primary" style="margin-left: 10px" icon="el-icon-search" @click="getTempJson()">获取温度JSON</el-button>
          <el-input v-model="currentRow.tempJson" type="textarea" :autosize="{ minRows: 8}"
                    placeholder="请输入值"></el-input>
        </el-form-item>
        <el-form-item label="备注说明" prop="value">
          <el-input v-model="currentRow.remark" type="textarea" :autosize="{ minRows: 2}"
                    placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <!-- 操作按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-white" @click="isShowDialog = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="validateForm">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {getVirtualDeviceList, virtualDeviceAddOrUpdate, virtualDeviceTempJson} from '@/services/model/sensor'
import Format from '@/utils/format'
// form表单校验规则
const RULES = {}
export default {
  data() {
    return {
      temp: {},
      form: {
        page: 1,
        pageSize: 10
      },
      rules: RULES, // 表单校验的规则
      tableList: [],
      isShowDialog: false, // 是否显示弹窗
      currentRow: {}, // 新增数据
      defaultProps: {
        children: 'subMenu',
        label: 'name'
      },
      typeList: ["Integer", "Double", "String", "JSON"],
    }
  },
  computed: {
    // 弹窗的title
    dialogTitle() {
      return this.currentRow.id ? '编辑模拟设备' : '新增模拟设备'
    },
  },
  filters: {
    // 时间格式化
    formatTimer(timer) {
      return Format(new Date(timer), 'yyyy-MM-dd hh:mm:ss')
    }
  },
  methods: {
    async getTempJson() {
      this.temp.pointId = this.currentRow.pointId
      if (this.temp.time) {
        if (typeof this.temp.time === "object") {
          this.temp.time = this.temp.time.getTime()
        }
      } else {
        this.$message({
          type: 'warning',
          title: '提示',
          center: true,
          message: '请选择日期'
        })
        return
      }
      if (!this.temp.pointId) {
        this.$message({
          type: 'warning',
          title: '提示',
          center: true,
          message: '请填写监测点id'
        })
        return
      }
      let res = await virtualDeviceTempJson(this.temp)
      this.currentRow.tempJson = res.data || {}
    },
    // 当前变化的节点
    // 获取当前的序号
    getIndex(index) {
      let param = (this.form.page - 1) * this.form.pageSize + index + 1
      return param
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.form.pageSize = val
      this.queryList()
    },
    /**
     * row  当前操作行的对象
     */
    handleEdit(row) {
      this.isShowDialog = true
      this.currentRow = JSON.parse(JSON.stringify(row))
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    // 当前页码改变
    handleCurrentChange(val) {
      this.form.page = val
      this.queryList()
    },
    // 处理删除
    async handleDelete(row) {
      let res = await roleDelete({id: row.id})
      if (res.code === 200) {
        this.$notify({
          type: 'success',
          title: '提示',
          message: '数据已删除'
        })
        this.queryList()
      }
    },
    async queryList() {
      // 由于在前端进行过滤，所以name不能传到后端
      let res = await getVirtualDeviceList(this.form)
      this.tableList = res.data?.records || []
      this.form.page = Number(res.data?.current)
      this.form.total = Number(res.data?.total)
    },
    // 新增数据
    handleAdd() {
      this.currentRow = {}
      this.isShowDialog = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    jsonHandel(dataJson) {
      try {
        dataJson = dataJson.replace(/ \+/g, '')
        dataJson = dataJson.replace(/[\r\n]/g, '')
        let parseJSON = JSON.parse(dataJson)
        JSON.stringify(parseJSON, null, 2)
        return true
      } catch (err) {
        return false;
      }
    },
    // 表单提交
    validateForm() {
      if (!this.jsonHandel(this.currentRow.dataJson)) {
        this.$message(
          {
            type: 'warning',
            showClose: true,
            message: '请传入正确JSON格式的数据Json！'
          })
        return
      }
      if (this.currentRow.tempJson && !this.jsonHandel(this.currentRow.tempJson)) {
        this.$message(
          {
            type: 'warning',
            showClose: true,
            message: '请传入正确JSON格式的温度Json！'
          })
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitData()
        }
      })
    },
    // 新增编辑提交数据
    async submitData() {
      // 根据ID判断使用新增还是编辑
      let res = await virtualDeviceAddOrUpdate(this.currentRow)
      if (res.code === 200) {
        this.$notify({
          type: 'success',
          title: '提示',
          message: this.currentRow.id ? '修改成功' : '添加成功'
        })
        this.isShowDialog = false
        this.queryList()
        return true
      }
    }

  },
  mounted() {
  },
  activated() {
    this.queryList()
  }
}
</script>

<style lang="less" scoped>

</style>
